import random
import time
import os

def clear_screen():
    """清屏函数"""
    os.system('cls' if os.name == 'nt' else 'clear')

def print_board(snake, food, width, height, score):
    """打印游戏界面"""
    clear_screen()
    
    # 打印顶部边框
    print('+' + '-' * width + '+')
    
    # 打印游戏区域
    for y in range(height):
        row = '|'
        for x in range(width):
            # 检查是否是蛇头
            if (x, y) == snake[0]:
                row += '@'
            # 检查是否是蛇身
            elif (x, y) in snake[1:]:
                row += 'O'
            # 检查是否是食物
            elif (x, y) == food:
                row += '*'
            else:
                row += ' '
        row += '|'
        print(row)
    
    # 打印底部边框
    print('+' + '-' * width + '+')
    print(f'得分: {score}')
    print('使用 WASD 键移动，按 Q 退出游戏')

def get_user_input():
    """获取用户输入（简化版，实际需要按Enter确认）"""
    import msvcrt
    if msvcrt.kbhit():
        key = msvcrt.getch().decode('utf-8').lower()
        return key
    return None

def main():
    """主函数"""
    # 设置游戏区域大小
    width = 20
    height = 10
    
    # 初始化蛇的位置（中间）
    snake = [(width // 2, height // 2), (width // 2 - 1, height // 2), (width // 2 - 2, height // 2)]
    
    # 初始化蛇的移动方向（右）
    direction = 'd'
    
    # 生成初始食物
    def generate_food():
        while True:
            food = (random.randint(0, width - 1), random.randint(0, height - 1))
            if food not in snake:
                return food
    
    food = generate_food()
    score = 0
    game_over = False
    
    print("贪吃蛇游戏 - 按Enter开始")
    input()
    
    while not game_over:
        # 打印游戏界面
        print_board(snake, food, width, height, score)
        
        # 获取用户输入
        key = get_user_input()
        if key:
            # 防止180度转向
            if (key == 'w' and direction != 's') or \
               (key == 's' and direction != 'w') or \
               (key == 'a' and direction != 'd') or \
               (key == 'd' and direction != 'a') or \
               key == 'q':
                if key == 'q':
                    game_over = True
                else:
                    direction = key
        
        # 获取蛇头位置
        head_x, head_y = snake[0]
        
        # 根据方向移动蛇头
        if direction == 'w':
            head_y -= 1
        elif direction == 's':
            head_y += 1
        elif direction == 'a':
            head_x -= 1
        elif direction == 'd':
            head_x += 1
        
        # 检查碰撞
        # 边界碰撞
        if head_x < 0 or head_x >= width or head_y < 0 or head_y >= height:
            game_over = True
        # 自身碰撞
        elif (head_x, head_y) in snake:
            game_over = True
        
        # 更新蛇的位置
        snake.insert(0, (head_x, head_y))
        
        # 检查是否吃到食物
        if (head_x, head_y) == food:
            score += 10
            food = generate_food()
            # 蛇吃到食物后不删除尾部，即增长
        else:
            # 没吃到食物则删除尾部，保持长度不变
            snake.pop()
        
        # 控制游戏速度
        time.sleep(0.5)
    
    print("游戏结束!")
    print(f'最终得分: {score}')

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n游戏已退出")
    finally:
        clear_screen()